package com.cooba.broadCastReceiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Process;
import android.util.Log;
import android.view.Gravity;
import android.widget.Toast;

import com.cooba.R;
import com.cooba.application.MyApplication;
import com.cooba.dialog.ComfirmDialog;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by Administrator on 2015/12/14.
 * 广播服务监听
 */
public class MyReceiver extends BroadcastReceiver {
    private static int lastType = -1;
    private Context mContext;
    private ComfirmDialog dialog;
    public static final String WIFI_STATE_CHANGED = "android.net.wifi.WIFI_STATE_CHANGED";
    private WifiManager manger;
    private JSONObject json;
    private boolean isfirst = true;
    private String lastBssid = "";
    private Boolean lastIsSuccess=false;

    @Override
    public void onReceive(Context context, Intent intent) {
        // log.debug("网络状态改变");
        mContext = context;
//        String action = intent.getAction();
//        Log.d("wei", "网络状态改变 action=" + action + " lastType=" + lastType + ",lastbssid=" + lastBssid);
//        // 获得网络连接服务
//        ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
//        NetworkInfo info = connManager.getActiveNetworkInfo();
//        NetworkInfo wifiNetInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
//        WifiManager mWifi = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
//        WifiInfo wifiInfo = mWifi.getConnectionInfo();
//        if (info == null || !connManager.getBackgroundDataSetting()) {
//            Log.d("wei", "您的网络连接已中断");
//            lastType = -1;
//        } else {
//            int netType = info.getType();
//            if (netType != lastType) {//网络类型变化
//                if (info.isConnected()) {
//                    //delay 5seconds
//                    if (wifiNetInfo.isConnected()) {
//                        lastBssid = wifiInfo.getBSSID();
//
//                    }
//                    Log.d("wei", "new connection was create...type:" + info.getTypeName() + " status"
//                            + info.getDetailedState());
//                    requestData();
//                } else {
//                    //delay 5seconds
//                    Log.d("wei", "the connection was broken...type:" + info.getTypeName() + " status"
//                            + info.getDetailedState());
//                }
//                lastType = netType;
//            } else if (netType == 1) {
//                if (wifiNetInfo.isConnected()) {
//                    if (!wifiInfo.getBSSID().equals(lastBssid)) {
//                        Log.d("wei", "wifi connection change...");
//                        lastBssid = wifiInfo.getBSSID();
//                        requestData();
//                    }
//                }
//
//            }
//        }

        String action = intent.getAction();
        if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
            ConnectivityManager connectMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo wifiNetInfo = connectMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

            WifiManager mWifi = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);

//            if (!mWifi.isWifiEnabled()) {
//                mWifi.setWifiEnabled(true);
//            }
            WifiInfo wifiInfo = mWifi.getConnectionInfo();

            //WIFI是否连接成功
            if (wifiNetInfo.isConnected()) {
                Toast.makeText(context, "WIFI已经连接上：" + wifiInfo.getSSID(), Toast.LENGTH_SHORT).show();
                requestData();
            }
//            else {
//                Toast.makeText(context, "WIFI连接异常", Toast.LENGTH_LONG).show();
//            }
        }

    }

    private HttpUtils httpUtils;

    private void requestData() {
        httpUtils = new HttpUtils();
        httpUtils.configDefaultHttpCacheExpiry(0);
        httpUtils.configCurrentHttpCacheExpiry(0);
        httpUtils.send(HttpRequest.HttpMethod.GET, "http://a.cooba.cc/macmark.json", null, new RequestCallBack<String>() {
            @Override
            public void onFailure(HttpException arg0, String arg1) {
                Log.e("wei", "车载数据获取失败");

                MyApplication application = MyApplication.getMyApplication();
                if (application.getIsStart()) {
                    application.setIsStart(false);
                } else if (lastIsSuccess){
                    dialog=new ComfirmDialog(mContext, R.style.custom_dialog, R.layout.dialog_comfirm, new ComfirmDialog.DialogListener() {
                        @Override
                        public void comfirm() {
                            Intent i = mContext.getPackageManager()
                                    .getLaunchIntentForPackage(mContext.getPackageName());
                            i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            mContext.startActivity(i);
                            android.os.Process.killProcess(Process.myPid());

                        }
                    });
                    dialog.setCanceledOnTouchOutside(false);
                    dialog.setCancelable(false);
                    android.view.Window window = dialog.getWindow();
                    window.setGravity(Gravity.CENTER);
                    dialog.show();
//                    dialog = new AlertDialog.Builder(mContext).setMessage("网络发生变化").setPositiveButton("确定", new DialogInterface.OnClickListener() {
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//                            Intent i = mContext.getPackageManager()
//                                    .getLaunchIntentForPackage(mContext.getPackageName());
//                            i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                            mContext.startActivity(i);
//                            android.os.Process.killProcess(Process.myPid());
//                        }
//                    }).show();
//                    dialog.setCanceledOnTouchOutside(false);
                }
            }

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Log.e("wei", "车载数据获取成功" + responseInfo.result);
                try {
                    json = new JSONObject(responseInfo.result);
                    String mac = json.get("MAC").toString();
                    MyApplication application = MyApplication.getMyApplication();
                    application.setIsInCar(true);
                    application.setMac(mac);
                    lastIsSuccess=true;
                    if (application.getIsStart()) {
                        application.setIsStart(false);
                    } else {
                        dialog=new ComfirmDialog(mContext, R.style.custom_dialog, R.layout.dialog_comfirm, new ComfirmDialog.DialogListener() {
                            @Override
                            public void comfirm() {
                                Intent i = mContext.getPackageManager()
                                        .getLaunchIntentForPackage(mContext.getPackageName());
                                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                mContext.startActivity(i);
                                android.os.Process.killProcess(Process.myPid());

                            }
                        });
                        dialog.setCanceledOnTouchOutside(false);
                        dialog.setCancelable(false);
                        android.view.Window window = dialog.getWindow();
                        window.setGravity(Gravity.CENTER);
                        dialog.show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

}

